package com.rjs.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 连接的时候显示时间
 * @author LiuZhenghua
 * 2017年12月19日 上午11:07:30
 */
public class TimeServerHandler extends ChannelInboundHandlerAdapter {

	//when a connection is established and ready to generate traffic(通信)
	@Override
	public void channelActive(final ChannelHandlerContext ctx) throws Exception {
		
		ByteBuf time = ctx.alloc().buffer(4);
		//ByteBuf has two pointers, one for reader operations and the other for write operations 
		//so it needn't invoking flip method.
		time.writeInt((int)(System.currentTimeMillis() / 1000));
		final ChannelFuture f = ctx.writeAndFlush(time);
		f.addListener(new ChannelFutureListener() {
			// a write request is finished
			public void operationComplete(ChannelFuture future) throws Exception {
				assert f == future;
				ctx.close();
			}
		});
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

	
}
